$(function () {
    initTable();

    // 查询按钮事件
    $('#btnSearch').on('click', function () {
        reloadTable();
    });

    // 添加按钮事件
    $('#btnAdd').on('click', function () {
        showStudentDlg();
    });
});

let layerIndex;

function initTable() {
    layui.use(['table', 'form'], function () {
        const table = layui.table;
        const form = layui.form;

        table.render({
            elem: '#studentTable',
            id: 'studentTableReload',
            url: '/api/student/list',
            method: 'get',
            page: true,
            limit: 10,
            limits: [10, 20, 50],
            where: getSearchParams(),
            cols: [[
                {type: 'checkbox'},
                {field: 'id', title: 'id', sort: true},
                {field: 'name', title: '姓名'},
                {field: 'sno', title: '学号'},
                {
                    field: 'sex', title: '性别', templet: function (d) {
                        return d.sex === '1' ? '男' : '女';
                    }
                },
                {field: 'age', title: '年龄', sort: true},
                {
                    title: '操作', align: 'center', templet: function (d) {
                        return '<button class="layui-btn layui-btn-xs" onclick="editStudent(' + d.id + ')">编辑</button>' +
                            '<button class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteStudent(' + d.id + ')">删除</button>';
                    }
                }
            ]],
            response: {
                statusCode: 200
            },
            parseData: function (res) {
                return {
                    code: 200,
                    msg: '',
                    count: res.total,
                    data: res.data
                };
            }
        });
    });
}

function reloadTable() {
    layui.use(['table'], function () {
        const table = layui.table;
        table.reload('studentTableReload', {
            where: getSearchParams(),
            page: {curr: 1}
        });
    });
}

function getSearchParams() {
    return {
        sno: $('#sno').val(),
        name: $('#name').val(),
        age: $('#age').val(),
        sex: $('#sex').val()
    };
}

function showStudentDlg(data = {}) {
    $('#studForm')[0].reset();
    layui.form.val("studFormFilter", data);
    layerIndex = layer.open({
        type: 1,
        title: data.id ? '编辑学生信息' : '添加学生信息',
        area: ['520px', 'auto'],
        content: $('#studForm'),
        success: function () {
            $('#btnOK').prop('disabled', false).removeClass('layui-btn-disabled');
            layui.form.render();
        }
    });
}

function editStudent(id) {
    $.get('/api/student/' + id, function (res) {
        if (res.id) {
            showStudentDlg(res);
        }
    });
}

function deleteStudent(id) {
    layer.confirm('确定要删除该学生信息吗？', {icon: 3, title: '提示'}, function (index) {
        $.ajax({
            url: '/api/student/' + id,
            type: 'delete'
        }).done(function (result) {
            if (result.success || result.code === 200) {
                layer.msg("删除成功！");
                reloadTable();
            }
        }).fail(function () {
            alert("删除失败，请稍后再试！");
        });
        layer.close(index);
    });
}

layui.use(['form'], function () {
    const form = layui.form;

    form.on('submit(stud-dlg)', function (data) {
        event.preventDefault();
        commitStudent();
        return false;
    });
});

function commitStudent() {
    const formData = $('#studForm').serialize();
    const idVal = $('#id').val();
    const url = idVal ? '/api/student/update' : '/api/student/add';

    $('#btnOK').prop('disabled', true).addClass('layui-btn-disabled');

    $.ajax({
        url: url,
        type: "post",
        data: formData
    }).done(function (result) {
        if (result.success || result.id) {
            layer.msg("操作成功！");
            layer.close(layerIndex);
            reloadTable();
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.error("请求失败:", textStatus + " - " + errorThrown);
        alert("操作失败，请稍后再试！");
    }).always(function () {
        $('#btnOK').prop('disabled', false).removeClass('layui-btn-disabled');
    });
}
